# coding:utf-8
import requests

from ..settings import PLUGINS_DIR


class Gitee:
    USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0'

    def send_request(self, url, method='GET', **kwargs):
        headers = {'User-Agent': self.USER_AGENT}
        response = requests.request(method, url, headers=headers, **kwargs)
        response.raise_for_status()
        response.encoding = 'utf-8'
        return response

    def plugins(self):
        url = 'https://gitee.com/api/v3/projects/chiyaun/python-tools-box/tree/master/plugins'
        rusult = self.send_request(url).json()
        for item in rusult:
            if item['path'] == 'plugins':
                return item['items']

    def _get_plugin_file(self, path: str):
        url = f'https://gitee.com/api/v3/projects/chiyaun/python-tools-box/tree/master/{path}'
        rusult = self.send_request(url).json()
        for item in rusult:
            if item['path'] == path:
                return item

    def _download_file(self, path: str):
        url = f'https://gitee.com/chiyaun/python-tools-box/raw/master/{path}'
        response = self.send_request(url)
        local_path = PLUGINS_DIR / path

        if local_path.suffix:
            local_path.parent.mkdir(parents=True, exist_ok=True)
        else:
            local_path.mkdir(parents=True, exist_ok=True)
        local_path.write_text(response.text, encoding='utf-8')

    def download_plugin(self, path: str):
        rusult = self._get_plugin_file(path)
        for item in rusult['items']:
            if item['type'] == 'blob':
                self._download_file(item['path'])

    def get_settings(self, name: str):
        url = f'https://gitee.com/chiyaun/python-tools-box/raw/master/plugins/{name}/config.json'
        response = self.send_request(url).json()
        return response


if __name__ == '__main__':
    g = Gitee()
    print(g.get_settings('json_format'))
